<template>
  <el-button :icon="Plus" class="primaryBth ml20 add" type="primary" @click="addOne" v-if="!unAdd">添加数据</el-button>
  <el-button :icon="Delete" class="primaryBth ml20 delete" type="primary" @click="subOne" v-if="!unSub">删除当前行</el-button>
  <el-button :icon="Edit" class="primaryBth ml20 edit" type="primary" @click="editOne" v-if="!unEdit">修改当前行</el-button>

  <el-dialog :close-on-click-modal="false" v-model="dialogVisible" :title="title === '添加' ? '添加' : '修改'" :width="width + '%'" draggable>
    <div class="flex AC" ref="JRef">
      <div v-for="(item, index) in tableHeader" :key="index" class="flex AC mb18 mr10">
        <span class="mr10">{{ item.label }}</span>

        <el-checkbox v-if="item.type === 'checkbox'" v-model="obj[item.prop]" :indeterminate="false" />

        <el-select
          v-else-if="item.type === 'select'"
          ref="select"
          v-model="obj[item.prop].selectValue"
          :multiple="item.multiple ? true : false"
          filterable
          @change=""
          :style="{ width: `${item.width ? item.width + 'px' : '130px'}` }"
          @visible-change="(visible: any) => SelectVisibleChange(visible, item, obj)"
        >
          <el-option v-for="option in item.options" :key="option.value" :label="option.label" :value="option" style="margin: 0 auto">
            <span v-if="option.LeftLabel" class="mr15 floatL">{{ option.LeftLabel }}</span>
            <span v-if="option.RightLabel" class="f13 span">{{ option.RightLabel }}</span>
          </el-option>
        </el-select>

        <el-select
          v-else-if="item.type === 'select' && item.allowC"
          ref="select"
          v-model="obj[item.prop].selectValue"
          filterable
          allow-create
          @change=""
          :style="{ width: `${item.width ? item.width + 'px' : '130px'}` }"
          @visible-change="(visible: any) => SelectVisibleChange(visible, item, obj)"
        >
          <el-option v-for="option in item.options" :key="option.value" :label="option.label" :value="option" style="margin: 0 auto">
            <span v-if="option.LeftLabel" class="mr15 floatL">{{ option.LeftLabel }}</span>
            <span v-if="option.RightLabel" class="f13 span">{{ option.RightLabel }}</span>
          </el-option>
        </el-select>

        <el-select
          :disabled="item.change && title === '修改'"
          v-else-if="item.type === 'selectJ'"
          ref="select"
          v-model="obj[item.prop]"
          filterable
          allow-create
          @change=""
          :style="{ width: `${item.width ? item.width + 'px' : '130px'}` }"
          @visible-change="(visible: any) => SelectVisibleChange(visible, item, obj)"
        >
          <el-option v-for="option in item.options" :key="option.value" :label="option.label" :value="option" style="margin: 0 auto">
            <span v-if="option.LeftLabel" class="mr15 floatL">{{ option.LeftLabel }}</span>
            <span v-if="option.RightLabel" class="f13 span">{{ option.RightLabel }}</span>
          </el-option>
        </el-select>

        <el-select-v2
          v-else-if="item.type === 'selectJV2' && item.allowC"
          v-model="obj[item.prop]"
          :options="item.options"
          allow-create
          @visible-change="(visible: any) => SelectVisibleChange(visible, item, obj)"
          filterable
          placeholder="请筛选"
          :style="{ width: `${item.width ? item.width + 'px' : '130px'}` }"
        >
          <template #default="{ item }: any">
            <span v-if="item.LeftLabel" class="f12 mr15 floatL" :style="{ width: `${item.width ? item.width + 'px' : '280px'}` }">{{
              item.LeftLabel
            }}</span>
            <span v-if="item.RightLabel" class="f12 span" style="flex: 1">{{ item.RightLabel }}</span>
          </template>
        </el-select-v2>

        <el-select-v2
          v-else-if="item.type === 'selectJV2'"
          v-model="obj[item.prop]"
          :options="item.options"
          @visible-change="(visible: any) => SelectVisibleChange(visible, item, obj)"
          filterable
          placeholder="请筛选"
          :style="{ width: `${item.width ? item.width + 'px' : '130px'}` }"
        >
          <template #default="scope">
            <span v-if="item.LeftLabel" class="f12 mr15 floatL" :style="{ width: `${item.width ? item.width + 'px' : '280px'}` }">{{
              item.LeftLabel
            }}</span>
            <span v-if="item.RightLabel" class="f12 span" style="flex: 1">{{ item.RightLabel }}</span>
          </template>
        </el-select-v2>
        <!-- 单个日期 -->
        <el-date-picker
          :disabled="item.change && title === '修改'"
          v-else-if="item.type === 'dateSingle2'"
          v-model="obj[item.prop]"
          type="date"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          style="width: 150px"
          class="AIC"
        />
        <el-date-picker
          :disabled="item.change && title === '修改'"
          v-else-if="item.type === 'dateSingleSeconds'"
          v-model="obj[item.prop]"
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          :placeholder="formatToDateTime()"
          :style="{ width: item.width + 'px' }"
          class="AIC"
        />
        <!-- 数字输入框 -->
        <el-input-number
          v-else-if="item.type === 'number'"
          v-model="obj[item.prop]"
          :min="0"
          :max="100000"
          :step="1"
          :style="item.precision ? { width: '150px' } : { width: '120px' }"
          :precision="item.precision"
          @keydown="(event:any) => handleKeyDown(event, index)"
        />
        <!-- Tree -->
        <el-tree-select
          v-else-if="item.type === 'treeJ'"
          v-model="obj[item.prop]"
          :data="item.treeData"
          :props="item.defaultProps"
          check-strictly
          :render-after-expand="false"
          style="width: 200px"
        />
        <!-- 上传图片 -->
        <div v-else-if="item.type === 'imgs'">
          <el-upload
            v-model:file-list="obj[item.prop]"
            multiple
            drag
            action="#"
            :auto-upload="false"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">拖拽上传图片 或<em> 点击上传</em></div>
          </el-upload>
        </div>

        <!-- 输入框 -->
        <el-input
          @keydown="(event:any) => handleKeyDown(event, index)"
          :disabled="item.change && title === '修改'"
          v-else
          v-model="obj[item.prop]"
          @change=""
          style="height: 26px"
          :style="{ width: `${item.width ? item.width + 'px' : '120px'}` }"
        ></el-input>
      </div>
      <el-button class="primaryBth ml20 mb18" type="primary" size="default" @click="confirmChange('change')"
        >确认{{ title === '添加' ? '添加' : '修改' }}</el-button
      >
    </div>
  </el-dialog>
</template>

<script lang="ts">
import { debounce } from 'lodash'
import { defineComponent, reactive, ref, type PropType, onMounted, watch } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { formatToDateTime } from '@/utils/dateUtil'
import { ElMessage, ElMessageBox } from 'element-plus'
import LoginWork from '@/utils/LoginWork'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'JDialog'
})
</script>

<script lang="ts" setup>
import { Delete, Edit, Search, Share, Upload, Plus } from '@element-plus/icons-vue'

const JRef = ref()
const handleKeyDown = (e: any, index: any) => {
  if (e.key === 'Enter' || e.keyCode === 13) {
    const focusableElements = JRef.value.querySelectorAll('.el-input__inner')
    // 阻止默认的回车行为（比如表单提交等）
    e.preventDefault()
    // 计算下一个可聚焦元素的索引，使用模运算 % 实现循环，当到达最后一个元素时，索引会回到0，即第一个元素
    const nextIndex = (index + 1) % focusableElements.length
    // 将焦点移动到下一个可聚焦元素
    focusableElements[nextIndex].focus()
  }
}

const dialogImageUrl = ref('')
const imgDialogVisible = ref(false)

const handleRemove: any['onRemove'] = (uploadFile: any, uploadFiles: any) => {}

const handlePictureCardPreview: any['onPreview'] = (uploadFile: any) => {
  dialogImageUrl.value = uploadFile.url!
  imgDialogVisible.value = true
}

const title = ref('添加')

const emits = defineEmits(['confirm', 'removeOne', 'clickAdd', 'SelectVChange', 'clickEdit'])

const dialogVisible = ref(false)
const props = defineProps({
  width: Number,
  tableHeader: Array as any,
  unSub: {
    type: Boolean,
    default: false
  },
  unAdd: {
    type: Boolean,
    default: false
  },
  unEdit: {
    type: Boolean,
    default: true
  },
  currentTableRow: {
    type: Object as any,
    default: () => {
      return {}
    }
  },
  getOptionList: {
    type: Function as any
  },
  unClearAdd: {
    type: Boolean as any,
    default: false
  }
})

const confirmChange = debounce((item: any) => {
  emits('confirm', obj.value, dialogVisible, title.value)
}, 500)

// 点击+触发函数
const obj = ref<any>({})
const addOne = () => {
  if (props.unClearAdd) {
    obj.value = JSON.parse(JSON.stringify(props.currentTableRow))
  } else {
    title.value = '添加'
    props.tableHeader.forEach((item: any) => {
      if (item.type === 'select') {
        obj.value[item.prop] = { selectValue: '' }
      } else {
        obj.value[item.prop] = ''
      }
    })
  }
  dialogVisible.value = true
  emits('clickAdd', obj.value)
}

// 删除
const subOne = () => {
  ElMessageBox.confirm('是否删除？', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      emits('removeOne')
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功'
      })
    })
}

// 修改
const editOne = () => {
  title.value = '修改'
  obj.value = JSON.parse(JSON.stringify(props.currentTableRow))
  //   if(obj.value.photoPath)
  if (Array.isArray(obj.value.photoPath)) {
    obj.value.photoPath = obj.value.photoPath.map((item: any, index: any) => {
      item = {
        name: index,
        url: item
      }
      return item
    })
  }
  dialogVisible.value = true
  emits('clickEdit', obj.value)
}
onMounted(() => {
  props.tableHeader.forEach((item: any) => {
    // 处理下拉框
    if (item.type === 'select') {
      obj.value[item.prop] = {
        selectValue: '',
        options: []
      }
    } else {
      obj.value[item.prop] = ''
    }
  })
  obj.value = JSON.parse(JSON.stringify(props.currentTableRow))
})
// 下拉框出现/隐藏时触发
const SelectVisibleChange = (visible: boolean, item: any, obj: any) => {
  if (visible === true && props.getOptionList) {
    props.getOptionList()
  } else {
    item.option = []
  }
  emits('SelectVChange', visible, item, obj)
}
</script>

<style lang="less" scoped>
:deep(.el-upload--picture-card) {
  --el-upload-picture-card-size: none;
}
.edit {
  background-color: #1c84c6 !important;
}

.add {
  background-color: #23c6c8 !important;
}

.delete {
  background-color: red !important;
}

:deep(.el-input__wrapper) {
  background-color: transparent;
  // height: 26px;
}

.AC {
  align-items: center;
  flex-wrap: wrap;
}

.span {
  float: right;
  color: var(--el-text-color-secondary);
}

.floatL {
  overflow: hidden;
  float: left;
}
</style>
